package com.ruoyi.util.jwt;

import com.ruoyi.system.vo.JwtResult;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class WxJwtUtil {
    // 令牌秘钥
    public static String generate(String openid, String key,Integer expireTimeSecond) {
        return Jwts.builder()
                .setSubject(openid)
                .setExpiration(new Date(System.currentTimeMillis()+expireTimeSecond*1000))
                .signWith(SignatureAlgorithm.HS256, key)
                .compact();
    }

    public static String parse(String token, String key) {
        return Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject();
    }

    /**
     * 静默解析 JWT：不抛异常，返回解析结果
     */
    public static JwtResult parseSilent(String token, String key) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token)
                    .getBody();

            long remaining = (claims.getExpiration().getTime() - System.currentTimeMillis()) / 1000;
            return new JwtResult(claims.getSubject(), remaining < 0, remaining);
        } catch (ExpiredJwtException e) {
            // 已过期也能拿到 subject
            long remaining = (e.getClaims().getExpiration().getTime() - System.currentTimeMillis()) / 1000;
            return new JwtResult(e.getClaims().getSubject(), true, remaining);
        } catch (Exception e) {
            // 格式错误、签名不对等
            return new JwtResult(null, true, -1);
        }
    }
}
